package top.scsoul.voes.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import top.scsoul.voes.common.core.domain.model.RoleSearchVo;
import top.scsoul.voes.common.core.domain.model.RoleVo;
import top.scsoul.voes.common.exception.SystemException;
import top.scsoul.voes.common.utils.ExcelExportDownloadUtil;
import top.scsoul.voes.common.core.domain.entity.Permission;
import top.scsoul.voes.common.core.domain.entity.Role;
import top.scsoul.voes.common.core.domain.entity.RolePermission;
import top.scsoul.voes.system.mapper.RoleMapper;
import top.scsoul.voes.system.mapper.RolePermissionMapper;
import top.scsoul.voes.system.mapper.UserMapper;
import top.scsoul.voes.system.mapper.UserRoleMapper;
import top.scsoul.voes.system.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * (Role)表服务实现类
 *
 * @author guolei
 * @since 2021-08-8 00:13:10
 */
@Slf4j
@Transactional
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Role queryById(Integer id) {
        return this.roleMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Role> queryAllByLimit(int offset, int limit) {
        return this.roleMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param roleVo 实例对象
     * @return 实例对象
     */
    @Override
    public Role insert(RoleVo roleVo) {
        if (roleMapper.queryByKeyWord(roleVo.getRoleKeyword()) != null) {
            throw new SystemException("该角色已存在");
        }

        Role role = new Role();
        role.setRoleKeyword(roleVo.getRoleKeyword());
        role.setRoleDesc(roleVo.getRoleDesc());
        roleMapper.insert(role);
        Role existsRole = roleMapper.queryByKeyWord(role.getRoleKeyword());
        List<Integer> permissionIds = roleVo.getPermissionIds();
        if (permissionIds != null && permissionIds.size() > 0) {
            permissionIds.forEach(pid -> {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(existsRole.getId());
                rolePermission.setPermissionId(pid);
                rolePermissionMapper.insert(rolePermission);
            });
        }
        return existsRole;
    }

    /**
     * 修改数据
     *
     * @param roleVo 实例对象
     * @return 实例对象
     */
    @Override
    public Role update(RoleVo roleVo) {
        Role existsRole = roleMapper.queryByKeyWord(roleVo.getRoleKeyword());
        if (existsRole == null) {
            throw new SystemException("不能修改角色标识符");
        }
        existsRole.setRoleKeyword(roleVo.getRoleKeyword());
        existsRole.setRoleDesc(roleVo.getRoleDesc());

        List<Integer> oldPermissionIds = new ArrayList<>();
        List<Permission> permissions = existsRole.getPermissions();
        if (permissions != null && permissions.size() > 0) {
            permissions.forEach(permission -> {
                oldPermissionIds.add(permission.getId());
            });
        }


        List<Integer> permissionIds = roleVo.getPermissionIds();
        if (permissionIds != null && permissionIds.size() > 0) {
            permissionIds.forEach(pid -> {
                if (oldPermissionIds.contains(pid)) {
                    oldPermissionIds.remove(pid);
                } else {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(existsRole.getId());
                    rolePermission.setPermissionId(pid);
                    rolePermissionMapper.insert(rolePermission);
                }
            });
        }

        if (oldPermissionIds.size() > 0) {
            oldPermissionIds.forEach(pid -> {
                rolePermissionMapper.deleteByRoleIdAndPermissionId(existsRole.getId(), pid);
            });
        }

        this.roleMapper.update(existsRole);
        return roleMapper.queryByKeyWord(roleVo.getRoleKeyword());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        int i = roleMapper.deleteById(id);
        rolePermissionMapper.deleteByRoleId(id);
        userRoleMapper.deleteByRoleId(id);
        return i > 0;
    }

    @Override
    public PageInfo<Role> queryAll(RoleSearchVo roleSearchVo, int currentPage, int pageSize) {
        Role role = new Role();
        role.setRoleKeyword(roleSearchVo.getRoleKeyWord());
        role.setRoleDesc(roleSearchVo.getRoleDesc());
        PageHelper.startPage(currentPage, pageSize);
        List<Role> roles = roleMapper.queryAll(role);
        return new PageInfo<Role>(roles);

    }

    @Override
    public List<Role> queryAll(Role role) {
        return roleMapper.queryAll(role);
    }

    @Override
    public void exportRole(List<Integer> ids, HttpServletResponse response) throws IOException {
        List<Role> roleList = roleMapper.queryByIds(ids);
        ExcelExportDownloadUtil.excelExport(response, roleList, Role.class, "角色信息表");
    }
}